import * as THREE from 'three';
import { useEffect } from 'react';
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
const App = () => {
  useEffect(() => {
    // 创建场景
    const scene = new THREE.Scene();

    //相机位置
    const width = window.innerWidth;// 窗口宽度
    const height = window.innerHeight;//窗口高度
    const k = width / height; //窗口宽高比
    const s = 200; // 三维场景显示范围控制系数，系数越大，显示的范围越大

    //创建相机对象
    const camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
    camera.position.set(0, 0, 500); //设置相机位置
    camera.lookAt(scene.position);//设置相机方向，指向的场景对象

    //创建渲染器对象
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(width, height);// 设置渲染区域尺寸

    document.body.appendChild(renderer.domElement);// body元素中插入canvas对象

    function render() {
      renderer.render(scene, camera);
    }
    const controls = new OrbitControls(camera, renderer.domElement);
    controls.addEventListener('change', () => {
      render()
    });

    // 修改点材质的shader
    function pointShader(shader) {
      shader.fragmentShader = shader.fragmentShader.replace(
        // 原来的给片元赋值的代码替换为新的代码
        'outgoingLight = diffuseColor.rgb;',
        [
          'outgoingLight = diffuseColor.rgb;',
          //点方形区域像素与中心0.5, 0.5构成的半径
          'float r = distance(gl_PointCoord, vec2(0.5, 0.5));',
          //大于半径0.5的片元舍弃掉，实现方点变圆点的渲染效果
          'if(r>0.5)discard;',
          'gl_FragColor = vec4( outgoingLight, diffuseColor.a );',
        ].join('\n')
      );
    }
    // 创建一个顶点缓冲几何体
    const geometry = new THREE.BoxGeometry(100, 100, 100);
    //点模型渲染几何体每个顶点
    const material = new THREE.PointsMaterial({
      color: 0xffffff,
      size: 10.0, //点大小
      onBeforeCompile:pointShader // 添加这项展示从方点变成圆点
    })
    // 生成带有材质的物体
    const cube = new THREE.Points(geometry, material);
    // 把物体添加进场景中
    scene.add(cube);
    render()



  }, [])
}
export default App;